/**   
 *    
 * 项目名称：SmartKungFu   
 * 类名称：RefundResultServiceImpl   
 * 类描述： 退款处理实现类   
 * 创建人：zhangl  
 * 创建时间：2016年12月6日 上午11:02:54   
 * 修改人：zhangl   
 * 修改时间：2016年12月6日 上午11:02:54   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.lst.dao.ClientAccomplishMapper;
import com.lst.dao.ClientGrowthMapper;
import com.lst.dao.ClientGrowthUsedMapper;
import com.lst.dao.ClientRefundMapper;
import com.lst.dao.ClientRollMapper;
import com.lst.dao.MstGradeMapper;
import com.lst.dao.OrderDetailMapper;
import com.lst.dao.RefundResultMapper;
import com.lst.model.ClientAccomplish;
import com.lst.model.ClientGrowth;
import com.lst.model.ClientGrowthUsed;
import com.lst.model.ClientRefund;
import com.lst.model.ClientRoll;
import com.lst.model.MstGrade;
import com.lst.model.MstUser;
import com.lst.model.OrderDetail;
import com.lst.model.RefundResult;
import com.lst.service.RefundResultService;
import com.lst.utils.DateUtil;

/**
 * @ClassName: RefundResultServiceImpl
 * @Description: 退款处理实现类
 * @author zhangl
 * @date 2016年12月6日 上午11:02:54
 *
 */
@Service("refundResultService")
public class RefundResultServiceImpl implements RefundResultService {
	
	private static Logger logger = Logger.getLogger("log");
	
	@Autowired
	private ClientRollMapper clientRollMapper ;
	
	@Autowired
	private ClientGrowthUsedMapper clientGrowthUsedMapper;
	
	@Autowired
	private ClientGrowthMapper clientGrowthMapper;
	
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	
	@Autowired
	private ClientRefundMapper clientRefundMapper;
	
	@Autowired
	private ClientAccomplishMapper clientAccomplishMapper;
	
	@Autowired
	private MstGradeMapper mstGradeMapper;
	
	@Autowired
	private RefundResultMapper dao;
	
	/* (非 Javadoc)
	 * <p>Title: deleteByPrimaryKey</p>
	 * <p>Description: </p>
	 * @param id
	 * @return
	 * @see com.lst.service.RefundResultService#deleteByPrimaryKey(java.lang.Integer)
	 */
	@Override
	public int deleteByPrimaryKey(Integer id) {
		return dao.deleteByPrimaryKey(id);
	}

	/* (非 Javadoc)
	 * <p>Title: insert</p>
	 * <p>Description: </p>
	 * @param record
	 * @return
	 * @see com.lst.service.RefundResultService#insert(com.lst.model.RefundResult)
	 */
	@Override
	public int insert(RefundResult record) {
		return dao.insert(record);
	}

	/* (非 Javadoc)
	 * <p>Title: insertSelective</p>
	 * <p>Description: </p>
	 * @param record
	 * @return
	 * @see com.lst.service.RefundResultService#insertSelective(com.lst.model.RefundResult)
	 */
	@Override
	public int insertSelective(RefundResult record) {
		return dao.insertSelective(record);
	}

	/* (非 Javadoc)
	 * <p>Title: selectByPrimaryKey</p>
	 * <p>Description: </p>
	 * @param id
	 * @return
	 * @see com.lst.service.RefundResultService#selectByPrimaryKey(java.lang.Integer)
	 */
	@Override
	public RefundResult selectByPrimaryKey(Integer id) {
		return dao.selectByPrimaryKey(id);
	}

	/* (非 Javadoc)
	 * <p>Title: updateByPrimaryKeySelective</p>
	 * <p>Description: </p>
	 * @param record
	 * @return
	 * @see com.lst.service.RefundResultService#updateByPrimaryKeySelective(com.lst.model.RefundResult)
	 */
	@Override
	public int updateByPrimaryKeySelective(RefundResult record) {
		return dao.updateByPrimaryKeySelective(record);
	}

	/* (非 Javadoc)
	 * <p>Title: updateByPrimaryKey</p>
	 * <p>Description: </p>
	 * @param record
	 * @return
	 * @see com.lst.service.RefundResultService#updateByPrimaryKey(com.lst.model.RefundResult)
	 */
	@Override
	public int updateByPrimaryKey(RefundResult record) {
		return dao.updateByPrimaryKey(record);
	}
	
	/**
	 * 
	 * @Title: dealRefund
	 * @Description: 退款处理
	 * @param @param cr
	 * @param @param isTicket
	 * @param @param isGrade
	 * @param @param isGradeValue
	 * @param @param sysUser
	 * @param @return    设定文件
	 * @return boolean    返回类型
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
	public boolean dealRefund(ClientRefund cr,boolean isTicket,boolean isGrade,boolean isGradeValue,BigDecimal refPrice,MstUser sysUser){
		Date startDate = new Date();
		logger.info("dealRefund begin: " + startDate);
		
		boolean flag = false;
		
		try {
			
			OrderDetail od = cr.getOd();
			
			ClientGrowth cg = cr.getCg();
			
			//退还优惠卷
			if(isTicket && od.getTicket() != null){
				ClientRoll upCr = new ClientRoll();
				upCr.setId(od.getReserved2());
				upCr.setUpdatedate(startDate);
				upCr.setUpdateuser(sysUser.getId());
				upCr.setEnabled(false);
				upCr.setIsdeleted(true);
				
				//验证优惠卷是否过期
				/*ClientRoll cheCr = clientRollMapper.selectByPrimaryKey(od.getTicket());
				if(startDate.after(cheCr.getEnddate())){
					upCr.setRollstatus(CommonEnum.SYSCODE_TICKET_DATED);
				} else {
					upCr.setRollstatus(CommonEnum.SYSCODE_TICKET_USEING);
				}*/
				
				clientRollMapper.updateByPrimaryKeySelective(upCr);
			}
			
			//返回功力等级使用
			if(isGrade && od.getGrade() != null){
				
				ClientGrowthUsed upCgu = new ClientGrowthUsed();
				upCgu.setId(od.getReserved1());
				upCgu.setEnabled(true);
				upCgu.setIsdeleted(true);
				upCgu.setUpdatedate(startDate);
				upCgu.setUpdateuser(sysUser.getId());
				
				clientGrowthUsedMapper.updateByPrimaryKeySelective(upCgu);
			}
			
			//退还功力值、用户功力等级
			if(isGradeValue && cg.getId() != null){
				//退还功力值、
				ClientGrowth upCg = new ClientGrowth();
				upCg.setId(cg.getId());
				upCg.setEnabled(false);
				upCg.setIsdeleted(true);
				upCg.setUpdatedate(startDate);
				upCg.setUpdateuser(sysUser.getId());
				
				//用户功力等级
				Map<String, Object> accMap = new HashMap<String, Object>(); 
				accMap.put("enabled", true);
				accMap.put("isDeleted", false);
				accMap.put("clientId", cr.getClientid());
				accMap.put("orderByClause","ca.grade desc");
				
				PageBounds pageBounds = new PageBounds();
				List<ClientAccomplish> cas = clientAccomplishMapper.queryByList(accMap, pageBounds);
				if(!cas.isEmpty()){
					ClientAccomplish ca = cas.get(0);
					Integer growthValue = Integer.valueOf((int) ca.getGrowthvalue().doubleValue()) - cg.getGrowthvalue();
					//得到减掉功力值的用户新等级
					accMap.put("orderByClause", "g.id asc");
					List<MstGrade> mstGrades = mstGradeMapper.queryByList(accMap, pageBounds);
					
					//获取更新后的用户等级
					Integer gradeId = 0;
					int len = mstGrades.size();
					for (int i = 0; i < len; i++) {
						if(i == len - 1){
							if(growthValue >= mstGrades.get(i).getGrovalue()){
								gradeId = mstGrades.get(i).getId();
								break;
							}
						}else{
							if(growthValue >= mstGrades.get(i).getGrovalue()
								&&
							   growthValue < mstGrades.get(i + 1).getGrovalue()){
								gradeId = mstGrades.get(i).getId();
								break;
							}
						}
						
					}
					
					if(gradeId.equals(ca.getGrade())){//等级未改变
						ca.setGrowthvalue(new BigDecimal(growthValue));
						ca.setUpdatedate(startDate);
						ca.setUpdateuser(sysUser.getId());
						clientAccomplishMapper.updateByPrimaryKeySelective(ca);
					} else {//等级发生改变
						for(ClientAccomplish tempCa : cas){
							if(tempCa.getGrade().equals(gradeId)){
								
								tempCa.setGrowthvalue(new BigDecimal(growthValue));
								tempCa.setUpdatedate(startDate);
								tempCa.setUpdateuser(sysUser.getId());
								clientAccomplishMapper.updateByPrimaryKeySelective(tempCa);
								
								//删除高级的等级
								Map<String, Object> delMap = new HashMap<String,Object>();
								delMap.put("clientId", cr.getClientid());
								delMap.put("grade", gradeId);
								clientAccomplishMapper.delList(delMap);
								
								break;
							}
						}
					}
					
				}
				
				clientGrowthMapper.updateByPrimaryKeySelective(upCg);
			}
			
			//更新订单详情
			orderDetailMapper.updateByPrimaryKeySelective(od);
			
			//更新退款申请
			clientRefundMapper.updateByPrimaryKeySelective(cr);
			
			//插入退款处理
			RefundResult rr = new RefundResult();
			rr.setCreatedate(startDate);
			rr.setCreateuser(sysUser.getId());
			rr.setEnabled(true);
			rr.setGrade(od.getGrade());
			rr.setGradevalue(cg.getGrowthvalue());
			rr.setGraprice(od.getGraprice());
			rr.setIsdeleted(false);
			rr.setOrderdetailid(od.getId());
			rr.setOrderid(od.getOrderid());
			rr.setRefprice(refPrice);
			rr.setRefundid(cr.getId());
			rr.setTicket(od.getTicket());
			rr.setTicprice(od.getTicprice());
			
			dao.insert(rr);
			
			flag = true;
			
		} catch (Exception e) {
			logger.error("dealRefund error: " ,e);
		}
		
		logger.info("dealRefund end run(s): " + DateUtil.calLastedTime(startDate));
		
		return flag;
	}

}
